﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.Reflection;
using System.Threading;
using NPOI.HSSF.UserModel;
using Comm;

namespace GetWebPageData
{
    public partial class GetBuyData : Form
    {
        public GetBuyData()
        {
            InitializeComponent();
        }

        private void GetBuyData_Load(object sender, EventArgs e)
        {
            tbx_y.Text = DateTime.Today.Year.ToString();

            DataTable dt = new DataTable();
            dt.Columns.Add("key");
            dt.Columns.Add("value");
            for (int i = 1; i <= 12; i++)
            {
                DataRow dr = dt.NewRow();
                dr[0] = i.ToString();
                dr[1] = i.ToString("00");
                dt.Rows.Add(dr);
            }
            cbx_m.DataSource = dt;
            cbx_m.DisplayMember = "key";
            cbx_m.ValueMember = "value";

            cbx_m.SelectedIndex = (DateTime.Today.Month - 1);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string strURL = "http://pospower.fast.org.tw/Prg70Mb/Pmb7101QryMembSale.aspx";


            Type tp = Type.GetTypeFromProgID("InternetExplorer.Application");
            object ie = Activator.CreateInstance(tp);

            tp.InvokeMember("Navigate", BindingFlags.InvokeMethod, null, ie, new object[] { strURL });
            // tp.InvokeMember("Visible", BindingFlags.SetProperty, null, ie, new object[] { true });

            int intWait = 0;
            bool blnBusy = false;
            int intState = 0;


            while (true)
            {
                Thread.Sleep(500);
                blnBusy = (bool)tp.InvokeMember("Busy", BindingFlags.GetProperty, null, ie, null);
                intState = (int)tp.InvokeMember("ReadyState", BindingFlags.GetProperty, null, ie, null);
                if (!blnBusy && (intState == 4)) break;
                if (intWait >= 10)
                {
                    return;
                }
                Thread.Sleep(1000);
                intWait++;
            }

            object doc = tp.InvokeMember("document", BindingFlags.GetProperty, null, ie, null);

            string strState = "";
            intWait = 0;

            while (true)
            {
                Thread.Sleep(500);
                strState = (string)tp.InvokeMember("readyState",
                                                    BindingFlags.GetProperty,
                                                    null,
                                                    doc,
                                                    null);
                if (strState.Equals("complete")) break;
                if (intWait >= 10)
                {
                    return;
                }
                Thread.Sleep(1000);
                intWait++;
            }

            object objAll = tp.InvokeMember("all", BindingFlags.GetProperty, null, doc, null);

            //重新設定值
            //先取得要填入的控制項
            //http://pospower.fast.org.tw/Prg70Mb/Pmb7101QryMembSale.aspx
            object ddlMembIdQry = tp.InvokeMember("ddlMembIdQry", BindingFlags.GetProperty, null, objAll, null);
            object dtQryB = tp.InvokeMember("dtQryB", BindingFlags.GetProperty, null, objAll, null);
            object dtQryE = tp.InvokeMember("dtQryE", BindingFlags.GetProperty, null, objAll, null);
            object ddlPageSize = tp.InvokeMember("gv1$ctl01$ddlPageSize", BindingFlags.GetProperty, null, objAll, null);
            object btnQry = tp.InvokeMember("btnQry", BindingFlags.GetProperty, null, objAll, null);
            //填入網頁內容
            string sd = string.Format("{0}/{1}/1", tbx_y.Text.Trim(), cbx_m.Text);
            string ed = string.Format("{0}/{1}/31", tbx_y.Text.Trim(), cbx_m.Text);
            tp.InvokeMember("value", BindingFlags.SetProperty, null, ddlMembIdQry, new object[] { "080" });
            tp.InvokeMember("value", BindingFlags.SetProperty, null, dtQryB, new object[] { sd });
            tp.InvokeMember("value", BindingFlags.SetProperty, null, dtQryE, new object[] { ed });

            tp.InvokeMember("value", BindingFlags.SetProperty, null, ddlPageSize, new object[] { "50" });
            tp.InvokeMember("click", BindingFlags.InvokeMethod, null, btnQry, null);

            //gv1$ctl01$ddlPageSize
            strState = "";
            intWait = 0;

            while (true)
            {
                Thread.Sleep(1000);
                strState = (string)tp.InvokeMember("readyState", BindingFlags.GetProperty, null, doc, null);
                if (strState.Equals("complete")) break;
                if (intWait >= 10)
                {
                    return;
                }
                Thread.Sleep(1000);
                intWait++;
            }
            //取得第二次送回的資料
            object objBody = tp.InvokeMember("body", BindingFlags.GetProperty, null, doc, null);

            // 這就是您要的網頁內容
            //string strHTML = (string)tp.InvokeMember("innerHTML", BindingFlags.GetProperty, null, objBody, null);

            string context = (string)tp.InvokeMember("innerHTML", BindingFlags.GetProperty, null, objBody, null);

            WebBrowser wb = new WebBrowser();
            wb.Navigate("");
            wb.ScriptErrorsSuppressed = true;
            //wb.Document.Write("<script type='text/javascript'>window.onerror = function(){};</script>" + context);
            wb.Document.Write(context);
            HtmlElementCollection tb = wb.Document.GetElementsByTagName("TABLE");
            tb = wb.Document.GetElementsByTagName("TABLE");
            HtmlElementCollection tr = tb[13].GetElementsByTagName("TR");

            //建立工作表
            //工作表名稱
            string sheetName = string.Format("{0}{1}", tbx_y.Text, cbx_m.SelectedValue);
            NPOIComFunction xls = new NPOIComFunction(@"C:\店鋪購買資料.xls");
            if (xls.Workbook.GetSheetIndex(sheetName) > -1)
            {
                xls.Workbook.RemoveSheetAt(xls.Workbook.GetSheetIndex(sheetName));
            }
            HSSFSheet sheet = xls.Workbook.CreateSheet(sheetName);
            CreateDataHeader(sheet);

            //輸出文字檔
            Stream st = new FileStream(@"C:\cc.txt", FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(st, Encoding.UTF8);
            sw.Write(context);
            sw.Write((string)tp.InvokeMember("innerHTML", BindingFlags.GetProperty, null, objBody, null));
            int rowcnt = 0;
            foreach (HtmlElement trElement in tr)
            {
                rowcnt++;
                if (rowcnt <= 3) continue;

                HtmlElementCollection td = trElement.GetElementsByTagName("TD");
                for (int i = 0; i < td.Count; i++)
                {
                    //if (i == 1) continue;
                    //sw.Write(td[i].InnerText);
                    int write_row = tr.Count - rowcnt;
                    if (write_row == 0) break;
                    sheet.CreateRow(write_row).CreateCell(0).SetCellValue(td[0].InnerText);
                    sheet.CreateRow(write_row).CreateCell(1).SetCellValue(td[2].InnerText);
                    sheet.CreateRow(write_row).CreateCell(2).SetCellValue(td[3].InnerText);
                    sheet.CreateRow(write_row).CreateCell(3).SetCellValue(Convert.ToInt32(td[4].InnerText.Replace(",", "")));
                }
                //sw.WriteLine("");
            }
            sw.Dispose();
            st.Dispose();
            xls.WriteToFile();
            wb.Dispose();
            //釋放資源
            Marshal.ReleaseComObject(ie);
            ie = null;



            //完成訊息
            MessageBox.Show("OK!");
            this.Close();
        }

        private void CreateDataHeader(HSSFSheet sheet)
        {
            sheet.CreateRow(0).CreateCell(0).SetCellValue("日期");
            sheet.CreateRow(0).CreateCell(1).SetCellValue("商品");
            sheet.CreateRow(0).CreateCell(2).SetCellValue("數量");
            sheet.CreateRow(0).CreateCell(3).SetCellValue("金額");
        }


    }
}
